package com.qf.web.controller;

import com.alibaba.druid.util.StringUtils;
import com.qf.domain.Goods;
import com.qf.domain.PageBean;
import com.qf.service.GoodsService;
import com.qf.service.impl.GoodsServiceImpl;
import com.qf.utils.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@WebServlet("/goodsservlet")
@MultipartConfig(maxFileSize = 5*1024*1024,maxRequestSize = 20*1024*1024)
public class GoodsServlet extends BaseServlet {
    //goodsservlet?method=getGoodsById&id=

    public String getGoodsById(HttpServletRequest request, HttpServletResponse response){
        String id = request.getParameter("id");
        if(StringUtil.isEmpty(id)){
            request.setAttribute("msg", "商品id不能为空");
            return "/message.jsp";
        }
        try {
            GoodsService goodsService=new GoodsServiceImpl();
            Goods goods=goodsService.selectById(Integer.parseInt(id));
            request.setAttribute("goods", goods);
            return "/goodsDetail.jsp";
        } catch (NumberFormatException e) {
            e.printStackTrace();
            request.setAttribute("msg", "查询失败"+e.getMessage());
            return "/message.jsp";
        }
    }


    //goodsservlet?method=getGoodsListByTypeId&pageNum=
    //goodsservlet?method=getGoodsListByTypeId&typeId=1
    public String getGoodsListByTypeId(HttpServletRequest request, HttpServletResponse response){
        String typeId = request.getParameter("typeId");
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");
        String goodName = request.getParameter("goodsName");

        int page_num=1;
        int page_size=8;

        try {
            if(!StringUtil.isEmpty(pageNum)){
                page_num=Integer.parseInt(pageNum);
                if(page_num<1){
                    page_num=1;
                }
            }
            if(!StringUtil.isEmpty(pageSize)){
                page_size=Integer.parseInt(pageSize);
                if(page_size<1){
                    page_size=8;
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        StringBuilder where =new StringBuilder(" where 1=1 ");
        List<Object> params=new ArrayList<>();
        if(!StringUtil.isEmpty(goodName)){
            where.append(" and name like ? ");
            params.add("%"+goodName+"%");
        }
        if(!StringUtil.isEmpty(typeId)){
            where.append(" and typeid=? ");
            params.add(typeId);
        }
        if(params.size()<=0){
            return "/goodsList.jsp";
        }

        try {
            GoodsService goodsService=new GoodsServiceImpl();
            PageBean<Goods> pageBean=goodsService.SelectByPage(page_num,page_size,where.toString(),params);
            System.out.println("pageBean = " + pageBean);
            request.setAttribute("typeId", typeId);
            request.setAttribute("goodsName", goodName);
            request.setAttribute("pageBean", pageBean);
            return "/goodsList.jsp";
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "redirect:/index.jsp";
    }


    //-----------------------------------------------------------后台-------------------------------------------------------------


    //goodsservlet?method=addGoods
    public String addGoods(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("text/html;charset=UTF-8");
        //1判断是否登录 admin
        //2获取前端数据
        String name = request.getParameter("name");
        String typeid = request.getParameter("typeid");
        String pubdate = request.getParameter("pubdate");
        String price = request.getParameter("price");
        String star = request.getParameter("star");
        String intro = request.getParameter("intro");
        //获取图片
        Part picture = request.getPart("picture");
        //非空验证
        if(StringUtils.isEmpty(name)){
            request.setAttribute("msg","商品名称不能为空");
            return "/admin/message.jsp";
        }
        if(StringUtils.isEmpty(typeid)){
            request.setAttribute("msg","商品类型不能为空");
            return "/admin/message.jsp";
        }
        if(StringUtils.isEmpty(pubdate)){
            request.setAttribute("msg","商品上架时间不能为空");
            return "/admin/message.jsp";
        }
        if(StringUtils.isEmpty(price)){
            request.setAttribute("msg","商品价格不能为空");
            return "/admin/message.jsp";
        }
        if(StringUtils.isEmpty(star)){
            request.setAttribute("msg","商品热销指数不能为空");
            return "/admin/message.jsp";
        }
        if(StringUtils.isEmpty(intro)){
            request.setAttribute("msg","商品介绍不能为空");
            return "/admin/message.jsp";
        }
        //3调用业务逻辑
        int type_id = Integer.parseInt(typeid);
        if(type_id<=0){
            request.setAttribute("msg","请选择合适类型");
            return "/admin/addGoods.jsp";
        }
        //处理图片
        //IE浏览器文件名问题
        String dis = picture.getHeader("Content-Disposition");
        String filename = dis.substring(dis.lastIndexOf("filename=") + 10, dis.length() - 1);//D:\bookcover\101.jpg
        filename = filename.substring(filename.lastIndexOf("\\") + 1);
        String uuidFileName=null;
        if (!filename.equals("")) {//文件名不为空上传图片
            //保存图片
            String basePath = this.getServletContext().getRealPath("WEB-INF" + File.separator + "images");
            File dir=new File(basePath);
            if (!dir.exists()) {
                dir.mkdirs();//创建多级目录
            }
            //获取后缀
            String ext=filename.substring(filename.lastIndexOf(".")+1);
            uuidFileName= UUID.randomUUID().toString().replace("-","");
            uuidFileName=uuidFileName+"."+ext;
            picture.write(basePath+File.separator+uuidFileName);
            picture.delete();
            System.out.println("保存图片成功");
        }
        try {
            GoodsService goodsService=new GoodsServiceImpl();
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            Goods goods=new Goods(0,name,sdf.parse(pubdate),uuidFileName,new BigDecimal(price),Integer.parseInt(star),intro,type_id);
            goodsService.insert(goods);
            response.getWriter().write("<script>alert('添加成功');window.location='admin/addGoods.jsp';</script>");
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("<script>alert('添加失败');window.location='admin/addGoods.jsp';</script>");
        }
        return null;
    }


    //goodsservlet?method=getGoodsList&name="+name+"&pubdate="+pubdate
    public String getGoodsList(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        String pubdate = request.getParameter("pubdate");
        List<Object> params = new ArrayList<>();
        StringBuilder where = new StringBuilder(" where 1=1 ");
        if (!StringUtils.isEmpty(name)) {
            where.append(" and name like ? ");
            params.add("%" + name + "%");
        }
        if (!StringUtils.isEmpty(pubdate)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                where.append(" and  pubdate = ? ");
                params.add(sdf.parse(pubdate));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }

        try {
            GoodsService goodsService = new GoodsServiceImpl();
            List<Goods> goodsList = goodsService.selectGoods(where.toString(), params);
            request.setAttribute("goodsList", goodsList);
            return "admin/showGoods.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "查询失败：" + e.getMessage());
            return "admin/message.jsp";
        }
    }


    //goodsservlet?method=deleteGoodsList&id=${goods.id}
    public String deleteGoodsList(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        try {
            GoodsService goodsService = new GoodsServiceImpl();
            goodsService.deleteById(id);
            return "redirect:/goodsservlet?method=getGoodsList";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "删除失败：" + e.getMessage());
            return "admin/message.jsp";
        }
    }

    //goodsservlet?method=findGoods&id=${goods.id}
    public String findGoods(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        System.out.println("id = " + id);
        try {
            GoodsService goodsService = new GoodsServiceImpl();
            Goods goods = goodsService.select(id);
            request.setAttribute("goods", goods);
            return "admin/updateGoods.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "失败：" + e.getMessage());
            return "admin/message.jsp";
        }
    }


    //goodsservlet?method=updateGoods
    public String updateGoods(HttpServletRequest request, HttpServletResponse response) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String pubdate = request.getParameter("pubdate");
        String price = request.getParameter("price");
        String star = request.getParameter("star");
        String intro = request.getParameter("intro");
        try {
            Goods goods=new Goods(Integer.parseInt(id),name,sdf.parse(pubdate),null,new BigDecimal(price),Integer.parseInt(star),intro,null);
            GoodsService goodsService=new GoodsServiceImpl();
            goodsService.update(goods);
            return "redirect:/goodsservlet?method=getGoodsList";
        } catch (ParseException e) {
            e.printStackTrace();
            request.setAttribute("msg", "失败：" + e.getMessage());
            return "admin/message.jsp";
        }
    }
}
